<!DOCTYPE html>
<html>
  <head>
    <script src="./node_modules/docx/build/index.umd.js"></script>
    <script src="./FileSaver.js"></script>
  </head>

  <body>
    <h1>未供即用监测</h1>

    <button type="button" id="button1">
      未供即用监测报告下载
    </button>

    <script>
      // var xhr = new XMLHttpRequest()
      // xhr.responseType = "json"
      // xhr.open("GET", "http://192.168.1.105:8091/exceltoword/selectWgjyshape?jcsj=2024Q3")
      // xhr.send()
      // xhr.onreadystatechange = function () {
      //   if (xhr.readyState == 4 && xhr.status == 200) {
      //     arr = xhr.response
      //     generate(arr)
      //     console.log(arr)
      //   }
      // }
      // var xhr1 = new XMLHttpRequest()
      // xhr1.responseType = "json"
      // xhr1.open("GET", "http://192.168.1.105:8091/exceltoword/selectWgjyNMKshape?jcsj=2024Q3")
      // xhr1.send()
      // xhr1.onreadystatechange = function () {
      //   if (xhr1.readyState == 4 && xhr1.status == 200) {
      //     arr1 = xhr1.response
      //     generate(arr1)
      //     console.log(arr1)
      //   }
      // }
      var xhr1 = new XMLHttpRequest();
      var xhr2 = new XMLHttpRequest();
      var arr, arr1;
      
      xhr1.responseType = "json";
      xhr1.open("GET", "http://192.168.1.105:8091/exceltoword/selectWgjyshape?jcsj=2024Q3"); 
      xhr1.send();
      
      xhr2.responseType = "json";
      xhr2.open("GET", "http://192.168.1.105:8091/exceltoword/selectWgjyNMKshape?jcsj=2024Q3"); 
      xhr2.send();
      
      Promise.all([
          new Promise((resolve, reject) => {
              xhr1.onreadystatechange = function () {
                  if (xhr1.readyState == 4) {
                      if (xhr1.status == 200) {
                          arr = xhr1.response;
                          resolve(arr);
                      } else {
                          reject(new Error(`Request 1 failed with status ${xhr1.status}`));
                      }
                  }
              };
          }),
          new Promise((resolve, reject) => {
              xhr2.onreadystatechange = function () {
                  if (xhr2.readyState == 4) {
                      if (xhr2.status == 200) {
                          arr1 = xhr2.response;
                          resolve(arr1);
                      } else {
                          reject(new Error(`Request 2 failed with status ${xhr2.status}`));
                      }
                  }
              };
          })
      ]).then(([result1, result2]) => {
          generate(arr, arr1);
          console.log(arr, arr1);
      }).catch(error => {
          console.error("One or both requests failed:", error);
      });
      function generate(arr, arr1) {
        // 创建一个字典（对象）来存储每个cou的area和percentage的总和
        const couSums = {};
        var areasum = 0;
        var countsum = 0;
        // 遍历原始数组，计算每个cou的总和，同时将area和percentage转换为数字
        arr.forEach(item => {
            const cou = item.cou;
            const area = parseFloat(item.area);
            const percentage = parseFloat(item.percentage);
            countsum += parseInt(item.tblxcount);
            
            if (!(cou in couSums)) {
                couSums[cou] = { area: 0, percentage: 0 };
            }
            couSums[cou].area += area;
            couSums[cou].percentage += percentage;
        });
        const conSumskeys = Object.keys(couSums);
        var sortArray = [];
        for (let key of conSumskeys) {
          areasum += couSums[key].area;
          var temp = {};
          temp.cou = key;
          temp.area = couSums[key].area;
          temp.percentage = couSums[key].percentage;
          sortArray.push(temp);
        }
        sortArray.sort((a, b) => b.area - a.area);
        console.log(couSums);
        console.log(sortArray);
        var arraylen = sortArray.length;
        var text_para2 = sortArray[0].cou + "和" + sortArray[1].cou + "疑似未供即用图斑面积较大，分别为" + parseFloat(sortArray[0].area).toFixed(2) + "亩，" + parseFloat(sortArray[1].area).toFixed(2)
                          + "亩，面积占比分别为" + parseFloat(sortArray[0].percentage).toFixed(2) + "%," + parseFloat(sortArray[1].percentage).toFixed(2) + "%。" + sortArray[arraylen-2].cou + "和" + sortArray[arraylen-1].cou
                          + "疑似未供即用图斑面积较小，分别为" + parseFloat(sortArray[arraylen-2].area).toFixed(2) + "亩，" + parseFloat(sortArray[arraylen-1].area).toFixed(2) 
                          + "亩，面积占比分别为" + parseFloat(sortArray[arraylen-2].percentage).toFixed(2) + "%," + parseFloat(sortArray[arraylen-1].percentage).toFixed(2) + "%。";
        

        var arraylen2 = arr1.length;
        var text_para3 = "将提取的变化图斑与2023年年末库地类相交，得到未供即用变化图斑占用地类情况（表2），按照占用面积从大到小排序，前五依次为" 
                        + arr1[0].dictdlbm + ",占用面积" + arr1[0].countarea + "亩，占比" + arr1[0].percentage + "%;"
                        + arr1[1].dictdlbm + ",占用面积" + arr1[1].countarea + "亩，占比" + arr1[1].percentage + "%;"
                        + arr1[2].dictdlbm + ",占用面积" + arr1[2].countarea + "亩，占比" + arr1[2].percentage + "%;"
                        + arr1[3].dictdlbm + ",占用面积" + arr1[3].countarea + "亩，占比" + arr1[3].percentage + "%;"
                        + arr1[4].dictdlbm + ",占用面积" + arr1[4].countarea + "亩，占比" + arr1[4].percentage + "%;"
        console.log(text_para3);               

        // 创建一个新数组来存储结果
        const newData = [];
        // 遍历原始数组，将每个项添加到新数组中，并在每个cou的最后添加总计项
        arr.forEach(item => {
            newData.push({ ...item }); // 使用{ ...item }创建对象的浅拷贝，以避免直接修改原始数组项
            const cou = item.cou;
            // 检查是否已经添加了该cou的总计项（通过查找town为"总计"且cou相同的项）
            const hasTotal = newData.some(x => x.town === "总计" && x.cou === cou);
            if (!hasTotal) {
                const totalItem = {
                    cou: cou,
                    area: couSums[cou].area.toFixed(2), // 将总和格式化为保留两位小数的字符串（如果需要）
                    town: "总计",
                    percentage: couSums[cou].percentage.toFixed(2) // 将百分比总和格式化为保留两位小数的字符串（如果需要）
                };
                newData.push(totalItem);
            }
        });
          
        // 按照cou的顺序排序，并确保总计项在每个cou的最后
        const sortedNewData = [];
        const couOrder = [...new Set(arr.map(item => item.cou))].sort((a, b) => a.localeCompare(b));
          
        couOrder.forEach(cou => {
            const couItems = newData.filter(item => item.cou === cou);
            const nonTotalItems = couItems.filter(item => item.town !== "总计");
            const totalItem = couItems.find(item => item.town === "总计");
            
            sortedNewData.push(...nonTotalItems);
            if (totalItem) {
                sortedNewData.push(totalItem);
            }
        });
          
        // 打印结果
        console.log(sortedNewData);

        const arr2 = arr1.map(item => ({
            ...item,
            countarea: parseFloat(item.countarea) 
        })).sort((a, b) => b.countarea - a.countarea); 

        var areasum = 0
        arr.reduce((accumulator, item) => {  
          areasum += parseFloat(item.area); 
          }, {});
        var areasum1 = 0
        arr2.reduce((accumulator, item) => {  
          areasum1 += parseFloat(item.countarea); 
          }, {});
        
        var rows = [
            new docx.TableRow({
                children: [
                  new docx.TableCell({
                    children: [new docx.Paragraph({ text: "县市区" }),],
                    verticalAlign: docx.VerticalAlign.CENTER,
                  }),
                  new docx.TableCell({
                    children: [new docx.Paragraph({ text: "镇名" }),],
                    verticalAlign: docx.VerticalAlign.CENTER,
                  }),
                  new docx.TableCell({
                    children: [
                      new docx.Paragraph({ text: "面积(亩)" }),
                    ],
                    verticalAlign: docx.VerticalAlign.CENTER,
                  }),
                  new docx.TableCell({
                      children: [
                      new docx.Paragraph({ text: "占比(%)" }),
                    ],
                    verticalAlign: docx.VerticalAlign.CENTER,
                  }),
                ],
            }),
        ]
        sortedNewData.forEach(item => {  
            rows.push(new docx.TableRow({  
                children: [  
                    new docx.TableCell({  
                        children: [new docx.Paragraph({ text: `${item.cou}` })],  
                        verticalAlign: docx.VerticalAlign.CENTER,  
                    }),  
                    new docx.TableCell({  
                        children: [new docx.Paragraph({ text: `${item.town}` })],  
                        verticalAlign: docx.VerticalAlign.CENTER,  
                    }),  
                    new docx.TableCell({  
                        children: [new docx.Paragraph({ text: `${parseFloat(item.area).toFixed(2)}` })],  
                        verticalAlign: docx.VerticalAlign.CENTER,  
                    }),
                    new docx.TableCell({  
                        children: [new docx.Paragraph({ text: `${parseFloat(item.percentage).toFixed(2)}` })],  
                        verticalAlign: docx.VerticalAlign.CENTER,  
                    }),  
                ],  
            }));  
        });
        rows.push(new docx.TableRow({  
            children: [  
                new docx.TableCell({  
                    children: [new docx.Paragraph({ text: "总计" })],  
                    verticalAlign: docx.VerticalAlign.CENTER,  
                }),  
                new docx.TableCell({  
                    children: [new docx.Paragraph({ text: `` })],  
                    verticalAlign: docx.VerticalAlign.CENTER,  
                }),
                new docx.TableCell({  
                    children: [new docx.Paragraph({ text: `${parseFloat(areasum).toFixed(2)}` })],  
                    verticalAlign: docx.VerticalAlign.CENTER,  
                }),
                new docx.TableCell({  
                    children: [new docx.Paragraph({ text: `100` })],  
                    verticalAlign: docx.VerticalAlign.CENTER,  
                }),
            ],  
        }));

        var rows1 = [
            new docx.TableRow({
                children: [
                  new docx.TableCell({
                    children: [new docx.Paragraph({ text: "地类编码" }),],
                    verticalAlign: docx.VerticalAlign.CENTER,
                  }),
                  new docx.TableCell({
                    children: [new docx.Paragraph({ text: "地类名称" }),],
                    verticalAlign: docx.VerticalAlign.CENTER,
                  }),
                  new docx.TableCell({
                    children: [
                      new docx.Paragraph({ text: "图斑面积" }),
                    ],
                    verticalAlign: docx.VerticalAlign.CENTER,
                  }),
                  new docx.TableCell({
                      children: [
                      new docx.Paragraph({ text: "占比(%)" }),
                    ],
                    verticalAlign: docx.VerticalAlign.CENTER,
                  }),
                ],
            }),
        ]
        arr2.forEach(item => {  
            rows1.push(new docx.TableRow({  
                children: [  
                    new docx.TableCell({  
                        children: [new docx.Paragraph({ text: `${item.dictType}` })],  
                        verticalAlign: docx.VerticalAlign.CENTER,  
                    }),  
                    new docx.TableCell({  
                        children: [new docx.Paragraph({ text: `${item.dictdlbm}` })],  
                        verticalAlign: docx.VerticalAlign.CENTER,  
                    }),  
                    new docx.TableCell({  
                        children: [new docx.Paragraph({ text: `${item.countarea}` })],  
                        verticalAlign: docx.VerticalAlign.CENTER,  
                    }),
                    new docx.TableCell({  
                        children: [new docx.Paragraph({ text: `${item.percentage}` })],  
                        verticalAlign: docx.VerticalAlign.CENTER,  
                    }),  
                ],  
            }));  
        });
        rows1.push(new docx.TableRow({  
            children: [  
                new docx.TableCell({  
                    children: [new docx.Paragraph({ text: "总计" })],  
                    verticalAlign: docx.VerticalAlign.CENTER,  
                }),  
                new docx.TableCell({  
                    children: [new docx.Paragraph({ text: `` })],  
                    verticalAlign: docx.VerticalAlign.CENTER,  
                }),
                new docx.TableCell({  
                    children: [new docx.Paragraph({ text: `${parseFloat(areasum1).toFixed(2)}` })],  
                    verticalAlign: docx.VerticalAlign.CENTER,  
                }),
                new docx.TableCell({  
                    children: [new docx.Paragraph({ text: `100` })],  
                    verticalAlign: docx.VerticalAlign.CENTER,  
                }),
            ],  
        }));
        const doc = new docx.Document({
          sections: [
            {
              children: [
                new docx.Paragraph({
                  text: "3.1成果分析",
                  heading: docx.HeadingLevel.HEADING_1,
                }),
                new docx.Paragraph({
                  text: `利用2024年第三季度芜湖市0.5米分辨率遥感影像对芜湖市已批未供范围内的图斑进行监测摸底，经过解译分析，未供即用监测专题提取变化图斑总数${countsum}个，总面积${parseFloat(areasum).toFixed(2)}亩。`,
                }),
                new docx.Paragraph({
                  text: text_para2,
                }),
                new docx.Paragraph({
                  text: "表1 芜湖市2024年第三季度未供即用监测图斑分类面积统计表（单位：亩）",
                  heading: docx.HeadingLevel.HEADING_3,
                  alignment: docx.AlignmentType.CENTER,
                }),
                new docx.Table({
                  rows: rows
                }),
                new docx.Paragraph({
                  text: text_para3,
                }),
                new docx.Paragraph({
                  text: "表2 芜湖市2024年第三季度未供即用监测图斑占用地类面积统计表（单位：亩）",
                  heading: docx.HeadingLevel.HEADING_3,
                  alignment: docx.AlignmentType.CENTER,
                }),
                new docx.Table({
                  rows: rows1
                }),
              ],
            },
          ],
        });
        var button1 = document.getElementById("button1")
          button1.addEventListener("click", function () {
            docx.Packer.toBlob(doc).then((blob) => {
            console.log(blob);
            saveAs(blob, "未供即用监测报告.docx");
            console.log("Document created successfully");
          });
        })
      }
    </script>
  </body>
</html>